package com.qzct.advices;



import com.qzct.entity.vo.ResultCode;
import com.qzct.entity.vo.ResultVo;
import com.qzct.exceptions.ApiException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class ControllerExceptionAdvice {

    @ExceptionHandler({BindException.class})
    public ResultVo MethodArgumentNotValidExceptionHandler(BindException e){
        Map<String, String> map = new HashMap<>();
        BindingResult bindingResult = e.getBindingResult();
        bindingResult.getFieldErrors().forEach((item)->{
            map.put(item.getField(),item.getDefaultMessage());
        });

        return ResultVo.error(ResultCode.VALIDATE_ERROR,map);
    }
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResultVo MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        Map<String, String> map = new HashMap<>();
        BindingResult bindingResult = e.getBindingResult();
        bindingResult.getFieldErrors().forEach((item)->{
            map.put(item.getField(),item.getDefaultMessage());
        });

        return ResultVo.error(ResultCode.VALIDATE_ERROR,map);
    }
    @ExceptionHandler(ApiException.class)
    public ResultVo APIExceptionHandler(ApiException e) {
        return  ResultVo.error(ResultCode.CUSTOM_ERROR,e.getMsg());

    }
    @ExceptionHandler(Exception.class)
    public ResultVo MainExceptionHandler(Exception e){
        return ResultVo.error(ResultCode.EXCEPTION_ERROR,e.getMessage());
    }
}
